const BASE_URL = 'http://localhost:8000' // 根据实际后端地址修改

const http = (options) => {
  return new Promise((resolve, reject) => {
    const { url, method, data } = options
    const token = wx.getStorageSync('access_token');
    const refreshToken = wx.getStorageSync('refresh_token')

    // 添加请求头
    const header = {
      'Content-Type': 'application/json',
      'Authorization': token ? `Bearer ${token}` : ''
    }

    wx.request({
      url: BASE_URL + url,
      method: method || 'GET',
      data,
      header,
      success: (res) => {
        if (res.statusCode === 401) { // token过期
          refreshTokenRequest(refreshToken).then(newToken => {
            // 重试原始请求
            options.header.Authorization = `Bearer ${newToken}`
            http(options).then(resolve).catch(reject)
          }).catch(() => {
            wx.removeStorageSync('access_token')
            wx.removeStorageSync('refresh_token')
            wx.redirectTo({ url: '/pages/login/login' })
          })
        } else {
          resolve(res.data)
        }
      },
      fail: reject,
      complete: () => {
        wx.hideLoading()
        this.onShow() // 增加页面刷新
      }
    })
  })
}

// token刷新专用方法
const refreshTokenRequest = (refreshToken) => {
    return new Promise((resolve, reject) => {
        wx.request({
            url: BASE_URL + '/api/v1/token/refresh/',
            method: 'POST',
            data: { refresh: refreshToken },
            success: (res) => {
                if (res.statusCode === 200) {
                    wx.setStorageSync('access_token', res.data.access);
                    wx.setStorageSync('refresh_token', res.data.refresh);
                    resolve(res.data.access);
                } else {
                    reject();
                }
            },
            fail: reject
        });
    });
};

module.exports = {
  http
}